﻿using MyToDo.Service;
using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BZhanHengjicvWPF.Services
{
    public class HttpRestClient
    {
        private readonly string apiUrl;
        protected readonly RestClient client;

        public HttpRestClient(string apiUrl)    
        {
            this.apiUrl = apiUrl;
            client = new RestClient(apiUrl);
        }

        public async Task<ApiResponse> ExcuteAsync(BaseRequest baseRequest)
        {
            var requset = new RestRequest(baseRequest.Method);
            requset.AddHeader("Content-Type", "application/json");
            if (baseRequest.Parameter != null)
                requset.AddParameter("param", JsonConvert.SerializeObject(baseRequest.Parameter), ParameterType.RequestBody);
            client.BaseUrl = new Uri(apiUrl + baseRequest.Route);
            var response = await client.ExecuteAsync(requset);
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
                return JsonConvert.DeserializeObject<ApiResponse>(response.Content);
            else
            {
                return new ApiResponse()
                {
                    Status = false,
                    Message = response.Content,
                    Result = null
                };
            }
        }
        public async Task<ApiResponse<T>> ExcuteAsync<T>(BaseRequest baseRequest)
        {
            var requset = new RestRequest(baseRequest.Method);
            requset.AddHeader("Content-Type", "application/json");
            if (baseRequest.Parameter != null)
                requset.AddParameter("param", JsonConvert.SerializeObject(baseRequest.Parameter), ParameterType.RequestBody);
            client.BaseUrl = new Uri(apiUrl + baseRequest.Route);
            var response = await client.ExecuteAsync(requset);
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
                return JsonConvert.DeserializeObject<ApiResponse<T>>(response.Content);
            else
            {
                return new ApiResponse<T>()
                {
                    Status=false,
                    Message = response.Content,
                };
            }
        }
    }
}
